//
//  LZHomeViewController.m
//  laziz_Merchant
//
//  Created by ZhaoDongBo on 2016/11/23.
//  Copyright © 2016年 XBN. All rights reserved.
//

#import "LZHomeViewController.h"
#import "LZMyCenterViewController.h"

#import "LZMyCollectionView.h"

#import "GVUserDefaults+LZProperties.h"
#import "UIViewController+NavigationItemSetting.h"
#import "UINavigationController+FDFullscreenPopGesture.h"
#import "UIViewController+NavigationItemSetting.h"
#import "LZFinancialSummaryViewController.h"
#import "LZOrderListViewController.h"
#import "LZCouponManagerListViewController.h"
#import "LZManagePicturesViewController.h"

#import "LZScanQRCodeViewController.h"
#import "LZManageReviewsViewController.h"
#import "LZStaffAccountListViewController.h"

#import "Masonry.h"
#import "LZUserInfoPresenter.h"
#import "LZMerchantInfoModel.h"
#import "MJExtension.h"
#import "LZUserModel.h"
#import "LZAlertView.h"
#import "LZLeadingViewPresenter.h"

#import "LZRestaurantAuthenticationViewController.h"
#import "LZMyMessageCenterViewController.h"
#import "LZMsgCenterPresenter.h"
#import "extobjc.h"
#import "LZManagePictureContentViewController.h"
#import "LZHomePresenter.h"

@interface LZHomeViewController () <LZMyCollectionViewDelegate>

@property (nonatomic, strong) UIImageView * bgImageView;
@property (nonatomic, strong) LZMyCollectionView * collectionView;
@property (nonatomic, assign) BOOL isShowLeadingView;

@property (nonatomic, strong) UICollectionViewFlowLayout * authLayout;//未认证
@property (nonatomic, strong) UICollectionViewFlowLayout * userInfoLayout;//认证通过

@property (assign, nonatomic) CGFloat lzAlpha;
@property (assign, nonatomic) CGFloat navbar_change_y;

@property (nonatomic, strong) LZUserInfoPresenter * userInfoPresenter;
@property (nonatomic, strong) __block LZMerchantInfoModel * merchantInfoModel;

@property (nonatomic, strong) NSMutableArray * imageArrays;
@property (nonatomic, strong) UIButton *msgCenterBtn;
@property (nonatomic, strong) UIView *msgPointView;
@property (nonatomic, strong) LZMsgCenterPresenter *msgPresenter;
@property (nonatomic, strong) LZHomePresenter *homePresenter;
@end

@implementation LZHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.umLogPageViewName = @"首页页面";
    // 判断是否切换了语言并弹提示框刷新UI
    [[LZLanguageManager shareInstance] showChangeLanguageAlert];
    
    self.isShowLeadingView = [LZLeadingViewPresenter isShowLeadingView];
    
    WS(weakSelf);

    self.lzAlpha = 0;
    self.navbar_change_y = SCREEN_WIDTH/375.0*(500-40)/2.0-64;
    self.userInfoPresenter = [[LZUserInfoPresenter alloc] init];
    self.msgPresenter = [[LZMsgCenterPresenter alloc] init];

    [self.view addSubview:self.bgImageView];
    [self.bgImageView makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.leading.mas_equalTo(0);
        make.trailing.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];
    
    [self.view addSubview:self.collectionView];
    
    
    self.collectionView.headerViewAuthButtonBlock = ^(id sender) {
        if ([GVUserDefaults standardUserDefaults].authType == kAuthType_noneAuth ) {
            LZRestaurantAuthenticationViewController* vc = [[LZRestaurantAuthenticationViewController alloc] init];
            [weakSelf.navigationController pushViewController:vc animated:YES];

        }else if ([GVUserDefaults standardUserDefaults].authType == kAuthType_waitAuth){
            LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"res_auth_wait", nil) andImage:nil cancelButtonTitle:nil otherButtonTitles:LZLocalizedString(@"confirm", nil),nil];
            [alert show];

        }else if ([GVUserDefaults standardUserDefaults].authType == kAuthType_rejectAuth){
            LZRestaurantAuthenticationViewController* vc = [[LZRestaurantAuthenticationViewController alloc] init];
            vc.regected = YES;
            [weakSelf.navigationController pushViewController:vc animated:YES];
            
        }

    };
    
    self.collectionView.didSelectRowBlock = ^(NSIndexPath * indexPath) {
        
        DLog(@"%ld, %ld", (long)indexPath.row, (long)indexPath.section);
        
        [weakSelf.homePresenter pushToVCBaseIndexPath:indexPath FromVC:weakSelf];
       
    };
        
    [self lz_setTitle:@"laziz!"];
    [self lz_setCustomBarAlpha:0];
    [self configureNavbar];

}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
  
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
    [self checkUserAuthStateForShowView];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    //注册从后台进入前台的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillEnterForeground)name:UIApplicationWillEnterForegroundNotification object:nil];
    self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = NO;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = YES;
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (BOOL)fd_prefersNavigationBarHidden {
    return YES;
}


#pragma mark - UI

- (void)configureNavbar
{
    self.msgCenterBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.msgCenterBtn.frame = CGRectMake(0, 0, 40, 40);
    [self.msgCenterBtn setImage:[UIImage imageNamed:@"home_msg"] forState:UIControlStateNormal];
    [self.msgCenterBtn addTarget:self action:@selector(msgBtnAction) forControlEvents:UIControlEventTouchUpInside];
    
    [self.msgCenterBtn addSubview:self.msgPointView];
    self.msgPointView.hidden = YES;
    [self.msgPointView makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(8);
        make.trailing.mas_equalTo(-8);
        make.size.mas_equalTo(CGSizeMake(8, 8));
    }];
    
    [self hiddenBarNavigationItemSetting:@[self.msgCenterBtn] type:NAVIGATIONITEMSETTING_RIGHT];
}

#pragma mark - public method

- (void)refreshMerchantInfo {
    self.isShowLeadingView = NO;
    [self getMerchantInfo];
    [self getMerchantPhoto];
}

#pragma mark - private method

- (void)msgBtnAction
{
    LZMyMessageCenterViewController *vc = [[LZMyMessageCenterViewController alloc] initWithNibName:@"LZMyMessageCenterViewController" bundle:nil];
    [self.navigationController pushViewController:vc animated:YES];
}


- (UICollectionViewFlowLayout *)getCurrentLayout {

    if ([GVUserDefaults standardUserDefaults].authType == kAuthType_completeAuth) {
        return self.userInfoLayout;
    }else {
        return self.authLayout;
    }
}

- (void)getMerchantInfo {
    WS(weakSelf);
    if ([LZUserModel Instance].isLogin) {
        [self.userInfoPresenter userGetMerchantInfoSuccess:^(id data) {
            DLog(@"%@", data);
            
            weakSelf.merchantInfoModel = [LZMerchantInfoModel mj_objectWithKeyValues:data[@"data"]];
            [LZUserModel Instance].merchantInfo = weakSelf.merchantInfoModel;
            [weakSelf.collectionView reloadData];
            
        } onFail:^(NSString *fail) {
            DLog(@"%@", fail);
        }];
    }
}


/**
 根据用户状态显示相关首页.
 */
- (void)checkUserAuthStateForShowView
{
    /* 消息中心按钮判断.因为最初说认证之前不显示,现在改为全程显示,所以下面的关于按钮是否显示的判断,都是基于用户是管理者还是员工,员工始终不显示的*/
    self.msgCenterBtn.hidden = NO;
    if ([GVUserDefaults standardUserDefaults].authType == kAuthType_completeAuth) {
        
        BOOL hiddenMsgBtn =  [self.homePresenter configureDataSourceAndIsHiddenMsgBtnByUserTypeWithCollectionView:self.collectionView];
        self.msgCenterBtn.hidden = hiddenMsgBtn;//是否显示消息中心按钮
        
        [self.collectionView setCollectionViewLayout:self.userInfoLayout animated:YES];
        // 如果显示引导页，则不进行接口请求
        if (self.isShowLeadingView) {
            if (![LZLeadingViewPresenter isShowLeadingView]) {
                [self refreshMerchantInfo];
                if (!hiddenMsgBtn) {
                    [self checkUnReadMsgCount];
                }
            }
        }
        else
        {
            [self refreshMerchantInfo];
            if (!hiddenMsgBtn) {
                [self checkUnReadMsgCount];
            }
        }
        [self.collectionView reloadData];
    }else if ([GVUserDefaults standardUserDefaults].authType == kAuthType_noneAuth){
        
        BOOL hiddenMsgBtn = [self.homePresenter configureDataSourceAndIsHiddenMsgBtnByUserTypeWithCollectionView:self.collectionView];
        self.msgCenterBtn.hidden = hiddenMsgBtn;//是否显示消息中心按钮
        [self.collectionView setCollectionViewLayout:self.authLayout animated:YES];
        
        if (!hiddenMsgBtn) {
            [self checkUnReadMsgCount];
        }
        
    }else{
        @weakify(self);
        [self startLoadingViewForView:self.view loadingViewUserInteractionEnabled:NO];
        [self.userInfoPresenter userGetMerchantInfoSuccess:^(id data) {
            DLog(@"%@", data);
            @strongify(self);
            [self stopLoadingViewForView:self.view];
            [GVUserDefaults standardUserDefaults].authType = [data[@"data"][@"state"] integerValue];
            if ([GVUserDefaults standardUserDefaults].authType == kAuthType_completeAuth) {
                //如果进入本页发现认证通过.提示用户退出app,重新进入.只有认证提交后才会走此接口.此方法.唯一的
                LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"message_res_auth_success_exit", nil) andImage:nil cancelButtonTitle:nil otherButtonTitles:LZLocalizedString(@"confirm", nil),nil];
                
                [alert show];
                
                alert.clickButtonIndexBlock = ^(NSInteger index) {
                    exit(0);
                };

            }else if ([GVUserDefaults standardUserDefaults].authType == kAuthType_waitAuth){
                
                BOOL hiddenMsgBtn = [self.homePresenter configureDataSourceAndIsHiddenMsgBtnByUserTypeWithCollectionView:self.collectionView];
                self.msgCenterBtn.hidden = hiddenMsgBtn;
                [self checkUnReadMsgCount];
                [self.collectionView setCollectionViewLayout:self.authLayout animated:YES];
                LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"res_auth_wait", nil) andImage:nil cancelButtonTitle:nil otherButtonTitles:LZLocalizedString(@"confirm", nil),nil];
                [alert show];
                [self.collectionView reloadData];
                
            }else {
                
                BOOL hiddenMsgBtn = [self.homePresenter configureDataSourceAndIsHiddenMsgBtnByUserTypeWithCollectionView:self.collectionView];
                self.msgCenterBtn.hidden = hiddenMsgBtn;
                [self checkUnReadMsgCount];
                [self.collectionView setCollectionViewLayout:self.authLayout animated:YES];
                
                [self.collectionView reloadData];
            }
            
        } onFail:^(NSString *fail) {
            DLog(@"%@", fail);
            @strongify(self);
            [self stopLoadingViewForView:self.view];
        }];
    }
    
}

- (void)getMerchantPhoto {
    
    WS(weakSelf);
    if ([LZUserModel Instance].isLogin) {
        self.imageArrays = [NSMutableArray array];
        [self.userInfoPresenter userGetlistMerchantHeadPhotoonSuccess:^(id data) {
            DLog(@"%@", data);
            
            NSMutableArray * temArray = [data objectForKey:@"data"];
            for (int i = 0; i < temArray.count; i++) {
                [weakSelf.imageArrays addObject:[temArray[i] objectForKey:@"maxPhoto"]];
            }
            
            if (weakSelf.imageArrays.count > 0) {
                weakSelf.collectionView.imageArray = self.imageArrays;
                [weakSelf.collectionView reloadData];
            }
            
        } onFail:^(NSString *fail) {
            DLog(@"%@", fail);
        }];
    }
}


/**
 检查是否有未读消息
 */
- (void)checkUnReadMsgCount
{
    @weakify(self);
   [self.msgPresenter checkWetherHaveUnReadMsgSuccess:^(NSInteger unReadCount) {
       @strongify(self);
//       [[UIApplication sharedApplication] setApplicationIconBadgeNumber:unReadCount];
       if (unReadCount > 0) {
           self.msgPointView.hidden = NO;
       }else{
           self.msgPointView.hidden = YES;
       }
   } Failure:^(NSString *fail) {
       @strongify(self);
       self.msgPointView.hidden = YES;
   }];
}


/**
 注册通知的方法.app从后台进入前台
 */
- (void)applicationWillEnterForeground
{
     [self checkUserAuthStateForShowView];
}

#pragma mark - detailViewDidScroll

- (void)detailViewDidScroll:(UIScrollView *)scrollView {
    
    CGFloat offsetY = scrollView.contentOffset.y;
    
    if (offsetY <= self.navbar_change_y) {
        CGFloat alpha = MIN(1, offsetY/self.navbar_change_y);
        self.lzAlpha = alpha;
    }
    else {
        self.lzAlpha = 1;
    }
    
    [self lz_setCustomBarAlpha:self.lzAlpha];
}

- (UIImageView *)bgImageView {

    if (_bgImageView == nil) {
        _bgImageView = [[UIImageView alloc] init];
        _bgImageView.image = [UIImage imageNamed:@"lz_bg_image"];
    }
    
    return _bgImageView;
}

- (UICollectionView *)collectionView {
    
    if (_collectionView == nil) {
        
        UICollectionViewFlowLayout * layout = [self getCurrentLayout];
        _collectionView = [[LZMyCollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) collectionViewLayout:layout];
        _collectionView.detailDelegate = self;
    }
    
    return _collectionView;
}

- (UICollectionViewFlowLayout *)authLayout {

    if (_authLayout == nil) {
        
        GET_SCREEN_WIDTH(screen_width);
        _authLayout = [[UICollectionViewFlowLayout alloc] init];
        _authLayout.itemSize = CGSizeMake(screen_width/2.0, 150);
        _authLayout.minimumInteritemSpacing = 0;
        _authLayout.minimumLineSpacing = 0;
        _authLayout.sectionInset = UIEdgeInsetsMake(1.f, 0, 1.f, 0);
        _authLayout.headerReferenceSize = CGSizeMake(screen_width, 235);
    }
    
    return _authLayout;
}


- (UICollectionViewFlowLayout *)userInfoLayout {

    if (_userInfoLayout == nil) {
        
        GET_SCREEN_WIDTH(screen_width);
        _userInfoLayout = [[UICollectionViewFlowLayout alloc] init];
        _userInfoLayout.itemSize = CGSizeMake(screen_width/2.0, 150);
        _userInfoLayout.minimumInteritemSpacing = 0;
        _userInfoLayout.minimumLineSpacing = 0;
        _userInfoLayout.sectionInset = UIEdgeInsetsMake(5.f, 0, 1.f, 0);
        _userInfoLayout.headerReferenceSize = CGSizeMake(screen_width, 334);
    }
    
    return _userInfoLayout;
}

- (UIView *)msgPointView
{
    if (!_msgPointView) {
        _msgPointView = [[UIView alloc] init];
        _msgPointView.backgroundColor = [UIColor redColor];
        _msgPointView.layer.cornerRadius = 4.;
        _msgPointView.layer.masksToBounds = YES;
    }
    
    return _msgPointView;
}

- (CGFloat)getAuthAlertTextHeight:(NSString *)text
{
    CGFloat h = [text boundingRectWithSize:CGSizeMake(SCREEN_WIDTH - 40, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:15]} context:nil].size.height;
    
    return h;
}

- (LZHomePresenter *)homePresenter
{
    if (!_homePresenter) {
        _homePresenter = [[LZHomePresenter alloc] init];
    }
    
    return _homePresenter;
}

@end
